package cn.yedong.system.service.impl;

import cn.yedong.basic.service.Impl.BaseServiceImpl;
import cn.yedong.system.domain.Role;
import cn.yedong.system.mapper.RoleMapper;
import cn.yedong.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    /**
     * 添加角色之后，需要添加权限和菜单
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        if(role.getId() != null && role.getPermissions().size() > 0){
            roleMapper.addRolePermissions(role.getId(),role.getPermissions());
        }
        if(role.getId() != null && role.getMenus().size() > 0){
            roleMapper.addRoleMenus(role.getId(),role.getMenus());
        }
    }

    /**
     * 删除角色之前先删除该角色的【权限】和【菜单】和【角色员工中间表】
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id) {
        //根据角色id删除权限
        roleMapper.delPermissionsByRoleId(id);
        //根据角色id删除菜单
        roleMapper.delMenusByRoleId(id);
        //根据角色id删除员工角色中间表
        roleMapper.delEmployeeRoleByRoleId(id);
        super.del(id);
    }

    /**
     * 修改
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        //根据角色id删除权限
        roleMapper.delPermissionsByRoleId(role.getId());
        //根据角色id删除菜单
        roleMapper.delMenusByRoleId(role.getId());
        if(role.getId() != null && role.getPermissions().size() > 0){
            roleMapper.addRolePermissions(role.getId(),role.getPermissions());
        }
        if(role.getId() != null && role.getMenus().size() > 0){
            roleMapper.addRoleMenus(role.getId(),role.getMenus());
        }
        super.update(role);
    }

    /**
     * 批量删除角色
     * @param ids
     */
    @Override
    @Transactional
    public void patchDel(List<Long> ids) {
        for (Long id : ids) {
            //直接调del方法操作
            del(id);
        }
    }
}
